package cliente_admin;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.security.KeyStore;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManagerFactory;

import org.w3c.dom.Document;

import common.MensajeConsulta;
import common.TraductorXMLConsultas;

public class ModuloConsultas {
	
	private final static String IP_SERVIDOR = "localhost";
	private final static int PUERTO_SERVIDOR = 7070;
	
	private final static String KS_PATH= "keystore/cliente_admin.jks";
	
	private BufferedWriter salida;
	private BufferedReader entrada;
    private SSLSocket socket_cliente;
    
    private TraductorXMLConsultas traductorXML;

	public ModuloConsultas(char[] pass_ks, char[] pass_keys){
		traductorXML=new TraductorXMLConsultas();
		
		   try {
			  
			   // load del archivo del keystore
			   	KeyStore key_store = KeyStore.getInstance("JKS");
		        InputStream keystoreStream = getClass().getClassLoader().getResourceAsStream(KS_PATH);
		        
		        // inicio del keymanager a partir del keystore
		         key_store.load(keystoreStream, pass_ks);
		         KeyManagerFactory key_manager = KeyManagerFactory.getInstance("SunX509");
		         key_manager.init(key_store, pass_keys);
		         
		         // inicio del trustmanager a partir del keystore
		         TrustManagerFactory trust_store = TrustManagerFactory.getInstance("SunX509");
		         trust_store.init(key_store);
		         
		         // establezco el keystorey truststore utilizado por el socket ssl
		         SSLContext ssl_context = SSLContext.getInstance("SSL");
		         ssl_context.init(key_manager.getKeyManagers(), trust_store.getTrustManagers(), null);
			   
				 SSLSocketFactory ssl_factory = ssl_context.getSocketFactory();
				 socket_cliente =(SSLSocket) ssl_factory.createSocket(IP_SERVIDOR, PUERTO_SERVIDOR);
		         
				 socket_cliente.startHandshake();
		         
		         
		         
				 salida = new BufferedWriter(new OutputStreamWriter(socket_cliente.getOutputStream()));
		          entrada = new BufferedReader(new InputStreamReader(socket_cliente.getInputStream()));
		         
		         
		   	}catch (Exception e) {
		   		System.err.println(e.getMessage());
		   	}
	}
	
	public void enviarConsulta(MensajeConsulta msj_consulta){
		try {
			String consultaXML = traductorXML.crearXMLConsulta(msj_consulta);
			
			 salida.write(consultaXML, 0, consultaXML.length());
			 salida.newLine();
			 salida.flush();
			 
			 String msj="FIN";
			 salida.write(msj, 0, msj.length());
			 salida.newLine();
			 salida.flush();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	public Document recibirRespuesta(){
		StringBuffer sb = new StringBuffer();
		try {
			String linea;
			while(!(linea=entrada.readLine()).equals("FIN")){
				//sb.append(linea+"\n");
				sb.append(linea);
			}
			
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return traductorXML.parsearXMLRespuesta(sb.toString()); // CUIDADO CUANDO SE ENVIA CONSULTA NO VALIDA!!!!!!!!!!!!!
	}
	
	public void cerrar(){
		
        try {
	        salida.write("TERMINAR", 0, "TERMINAR".length());
	   		salida.newLine();
	   		salida.flush();
	   		
	   		String msj="FIN";
			 salida.write(msj, 0, msj.length());
			 salida.newLine();
			 salida.flush();
        	try {
				Thread.sleep(750);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        	salida.close();
            entrada.close();
			socket_cliente.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
